import 'package:dio/dio.dart';
import 'package:image_picker/image_picker.dart';
import '../models/user.dart';
import './http_client.dart';

class UserService {
  final HttpClient _httpClient = HttpClient();

  /// 获取用户个人信息
  Future<User> getUserProfile() async {
    final result = await _httpClient.get('/system/user/profile');
    return User.fromJson(result['data']);
  }

  /// 更新用户个人信息
  Future<bool> updateUserProfile({
    required String nickName,
    required String sex,
    String? email,
    String? phonenumber,
    String? avatar,
  }) async {
    try {
      await _httpClient.put('/system/user/profile', data: {
        'nickName': nickName,
        'sex': sex,
        if (email != null) 'email': email,
        if (phonenumber != null) 'phonenumber': phonenumber,
        if (avatar != null) 'avatar': avatar,
      });
      return true;
    } catch (e) {
      rethrow;
    }
  }

  /// 仅上传头像文件到OSS，不更新数据库
  Future<String> uploadAvatarOnly(XFile imageFile) async {
    try {
      // 只上传文件到OSS获取URL，不更新数据库
      final avatarUrl = await uploadAvatar(imageFile);
      return avatarUrl;
    } catch (e) {
      rethrow;
    }
  }

  /// 上传用户头像
  Future<String> uploadAvatar(XFile imageFile) async {
    try {
      // 创建FormData
      final formData = FormData.fromMap({
        'file': await MultipartFile.fromFile(
          imageFile.path,
          filename: imageFile.name,
        ),
      });

      final result = await _httpClient.post(
        '/file/upload/oss',
        data: formData,
      );

      // 根据OSS上传接口返回的数据结构提取URL
      final data = result['data'];
      String imageUrl;
      if (data is String) {
        imageUrl = data;
      } else if (data is Map && data['url'] != null) {
        imageUrl = data['url'];
      } else if (data is Map && data['fileName'] != null) {
        imageUrl = data['fileName'];
      } else {
        imageUrl = data.toString();
      }
      
      return imageUrl;
    } catch (e) {
      rethrow;
    }
  }

  /// 修改密码
  Future<bool> updatePassword({
    required String oldPassword,
    required String newPassword,
  }) async {
    try {
      await _httpClient.put('/system/user/profile/updatePwd', data: {
        'oldPassword': oldPassword,
        'newPassword': newPassword,
      });
      return true;
    } catch (e) {
      rethrow;
    }
  }
}